const request = require('request-promise');
const getHeaders = require('./getHeaders');

const headers = getHeaders();
const common = {
    jar: true,
    method: 'POST',
    gzip: true,
    headers,
};
const LIST_URL = 'https://www.wegame.com.cn/api/v1/wegame.pallas.game.LolBattle/GetBattleList';
const DETAIL_URL = 'https://www.wegame.com.cn/api/v1/wegame.pallas.game.LolBattle/GetBattleDetail';

module.exports = async ({ qq, id, count, area }) => {
    const listRes = await Promise.all(
        Array.from({ length: Math.ceil(count / 10 ) }).map((_i, index) => request({
            ...common,
            url: LIST_URL,
            body: JSON.stringify({
                account_type: 1,
                area,
                id: qq,
                count: index === Math.ceil(count / 10) - 1 ? (count === 10 ? count : count % 10) : 10,
                filter: '',
                offset: index * 10,
                from_src: 'lol_helper'
            }),
        })),
    )
    const listResult = {
        battles: [],
    };
    listRes.forEach(item => listResult.battles.push(...(JSON.parse(item).battles)));
    let result = {};
    const battles = listResult?.battles || [];
    result.list = battles;
    await Promise.all(battles.map(item => {
        return request({
            ...common,
            url: DETAIL_URL,
            body: JSON.stringify({
                account_type: 2,
                area,
                id,
                game_id: item.game_id,
                from_src: 'lol_helper',
            }),
        }).then(res => {
            const detailResult = JSON.parse(res);
            result.list.find(i => i.game_id === item.game_id).battle_detail = detailResult.battle_detail;
        });
    }));
    return result;
}